import 'package:flutter/material.dart';
import '../../models/page_state.dart';
import '../../viewmodels/base_view_model.dart';
import 'loading_more_widget.dart';
import 'no_more_data_widget.dart';

/// 可刷新的列表视图组件
/// 支持下拉刷新和上拉加载更多功能
class RefreshableListView<T> extends StatelessWidget {
  final BaseViewModel viewModel;
  final List<T> items;
  final Widget Function(T item, int index) itemBuilder;
  final VoidCallback onRefresh;
  final VoidCallback onLoadMore;
  final bool hasMore;
  final EdgeInsetsGeometry? padding;
  final ScrollController? controller;
  
  const RefreshableListView({
    super.key,
    required this.viewModel,
    required this.items,
    required this.itemBuilder,
    required this.onRefresh,
    required this.onLoadMore,
    this.hasMore = true,
    this.padding,
    this.controller,
  });
  
  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: () async => onRefresh(),
      child: ListView.builder(
        controller: controller,
        padding: padding,
        itemCount: items.length + 1,
        itemBuilder: (context, index) {
          if (index == items.length) {
            // 底部加载指示器
            if (viewModel.state == PageState.loading && items.isNotEmpty) {
              return const LoadingMoreWidget();
            } else if (viewModel.state == PageState.noMore || !hasMore) {
              return const NoMoreDataWidget();
            }
            return const SizedBox.shrink();
          }
          
          // 预加载逻辑：当滚动到 70% 位置时触发加载更多
          if (index >= items.length * 0.7 && 
              viewModel.state != PageState.loading &&
              hasMore) {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              onLoadMore();
            });
          }
          
          return itemBuilder(items[index], index);
        },
      ),
    );
  }
}